import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useAppStore = defineStore('app', {
  state: () => ({
    sidebar: {
      collapsed: false,
      withoutAnimation: false
    },
    device: 'desktop',
    size: 'default',
    language: 'zh-CN',
    theme: 'light',
    tagsView: [],
    cachedViews: [],
    settings: {
      showSettings: false,
      showTagsView: true,
      showSidebarLogo: true,
      fixedHeader: true,
      sidebarTextTheme: true,
      dynamicTitle: true
    }
  }),

  actions: {
    toggleSidebar() {
      this.sidebar.collapsed = !this.sidebar.collapsed
      this.sidebar.withoutAnimation = false
    },
    
    closeSidebar(withoutAnimation) {
      this.sidebar.collapsed = true
      this.sidebar.withoutAnimation = withoutAnimation
    },
    
    toggleDevice(device) {
      this.device = device
    },
    
    setSize(newSize) {
      this.size = newSize
    },
    
    setLanguage(lang) {
      this.language = lang
    },
    
    setTheme(newTheme) {
      this.theme = newTheme
      // 应用主题
      document.documentElement.setAttribute('data-theme', newTheme)
    },
    
    addTagsView(view) {
      if (this.tagsView.some(v => v.path === view.path)) return
      this.tagsView.push(
        Object.assign({}, view, {
          title: view.meta?.title || 'unknown'
        })
      )
    },
    
    removeTagsView(view) {
      const index = this.tagsView.findIndex(v => v.path === view.path)
      if (index > -1) {
        this.tagsView.splice(index, 1)
      }
    },
    
    addCachedView(view) {
      if (this.cachedViews.includes(view)) return
      if (view.meta && view.meta.cache !== false) {
        this.cachedViews.push(view)
      }
    },
    
    removeCachedView(view) {
      const index = this.cachedViews.indexOf(view)
      if (index > -1) {
        this.cachedViews.splice(index, 1)
      }
    },
    
    delAllCachedViews() {
      this.cachedViews = []
    },
    
    updateSettings(newSettings) {
      this.settings = { ...this.settings, ...newSettings }
    }
  },

  persist: {
    enabled: true,
    strategies: [
      {
        key: 'app',
        storage: localStorage,
        paths: ['sidebar', 'size', 'language', 'theme', 'settings']
      }
    ]
  }
}) 